package com.hj.ct.activity;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.hj.ct.App;
import com.hj.ct.R;
import com.hj.ct.db.dao.DeviceDao;
import com.hj.ct.fragment.LineChartFragment;
import com.hj.ct.logic.GatherDataLogic;
import com.hj.ct.parse.Device;
import com.hj.ct.view.ListPopupWindow;
import com.hj.ct.view.WheelDialog;
import com.hj.ct.view.WheelDialog.OnMyOnPickListener;

public class LineChartActivity extends BaseActivity implements OnClickListener {

	private TextView tvTimeFilter, tvDeviceFilter;
	private ListPopupWindow mPopupWindow;
	private View viewTitle;
	private Button btnRealChart;
	private Fragment lineChartFragment;
	private String deviceId;
	private String deviceName;

	private DeviceDao deviceDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_table);
		deviceDao = new DeviceDao(App.getContext());
		deviceId = getIntent().getStringExtra("deviceId");
		deviceName = getIntent().getStringExtra("deviceName");
		startTime = getIntent().getLongExtra("startTime", startTime);
		dur = getIntent().getIntExtra("dur", dur);
		loadDataType = getIntent().getIntExtra("loadDataType", loadDataType);
		timeFilter = Arrays.asList(getResources().getStringArray(R.array.time_filter));
//		timeFilterInt = getResources().getIntArray(R.array.time_filter_int);
		timeFilter.set(0, getIntent().getStringExtra("timeFilter"));
		initView();
		initFragment();
		tvTimeFilter.setText(getIntent().getStringExtra("tvTimeFilter"));
		tvDeviceFilter.setText(deviceName);
		if (loadDataType == 0) {
			loadDataShortcut();
		} else {
			loadDataDur();
		}
	}

	private void initFragment() {
		lineChartFragment = new LineChartFragment();
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		transaction.add(R.id.fragment, lineChartFragment);
		transaction.commit();
	}

	private void initView() {
		tvTimeFilter = (TextView) findViewById(R.id.tv_time_filter);
		btnRealChart = (Button) findViewById(R.id.btn_real_chart);
		viewTitle = findViewById(R.id.viewTitle);
		tvDeviceFilter = (TextView) findViewById(R.id.tv_device_filter);

		tvTimeFilter.setOnClickListener(this);
		tvDeviceFilter.setOnClickListener(this);
		btnRealChart.setOnClickListener(this);

		btnRealChart.setText("表格 >");
	}

	private List<String> timeFilter = null;
//	private int[] timeFilterInt = null;

	private void initTimeFilterPopupWindow() {
		if (mPopupWindow == null) {
			mPopupWindow = new ListPopupWindow(this);
		}
		mPopupWindow.setData(timeFilter);
		mPopupWindow.showAsDropDown(viewTitle);
		mPopupWindow.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (position == 0) {
					initStartDate();
				} else if (position == 1) {
					initDurDate();
				} else {
					tvTimeFilter.setText(mPopupWindow.getItem(position));
					mPopupWindow.dismiss();
					// dur = timeFilterInt[position];
					dur = computerShortcutDur(position);
					loadDataShortcut();
				}
			}
		});
	}

	private List<Device> devices;

	private void initDeviceFilterPopupWindow() {
		if (mPopupWindow == null) {
			mPopupWindow = new ListPopupWindow(this);
		}
		if (devices == null) {
			devices = deviceDao.getDevices();
		}
		List<String> data = new ArrayList<String>();
		for (int i = 0; i < devices.size(); i++) {
			data.add(devices.get(i).getDeviceName());
		}
		mPopupWindow.setData(data);
		mPopupWindow.showAsDropDown(viewTitle);
		mPopupWindow.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				tvDeviceFilter.setText(mPopupWindow.getItem(position));
				mPopupWindow.dismiss();
				deviceId = devices.get(position).getDeviceID();
				deviceName = devices.get(position).getDeviceName();
				tvDeviceFilter.setText(deviceName);
				if (loadDataType == 0) {
					loadDataShortcut();
				} else {
					loadDataDur();
				}
			}
		});
	}

	public static final int[] itemColors = { R.color.gray_eeeeee, R.color.white };

	public void onClick(View v) {
		if (v == tvTimeFilter) {
			initTimeFilterPopupWindow();
		} else if (v == tvDeviceFilter) {
			initDeviceFilterPopupWindow();
		} else if (v == btnRealChart) {
			finish();
		}
	}

	private long startTime = 0;
	private int dur = 0;
	private int loadDataType = 0;

	public int getDur() {
		return dur;
	}

	private void initStartDate() {
		WheelDialog dialog = new WheelDialog(this);
		if (timeFilter == null) {
			timeFilter = Arrays.asList(getResources().getStringArray(R.array.time_filter));
		}
		String time = timeFilter.get(0);
		if (!TextUtils.isEmpty(time) && !time.equals("起始时间")) {
			int monthNow = 0, dayOfMonthNow = 0, hourOfDayNow = 0;
			int newyear = 0;
			try {
				String[] dateArr = time.split("-");
				if (dateArr.length >= 3) {
					newyear = Integer.parseInt(dateArr[0]);
					monthNow = Integer.parseInt(dateArr[1]) - 1;
					String[] s = dateArr[2].split(" ");
					dayOfMonthNow = Integer.parseInt(s[0]) - 1;
					hourOfDayNow = Integer.parseInt(s[1]);
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
				return;
			}

			SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH");
			Date startDay;
			Calendar cal = null;
			try {
				startDay = sFormat.parse(time);
				cal = Calendar.getInstance();

				if (cal.before(startDay)) {
					throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
				}

			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return;
			}
			int year = newyear - 1902;
			String firstdata = "年,1902," + Calendar.getInstance().get(Calendar.YEAR) + ",false," + year;
			String seconddata = "月,1,12,true," + monthNow;
			String thirddata = "日,1,31,true," + dayOfMonthNow;
			String fourthdata = "时,0,23,true," + hourOfDayNow;
			dialog.setData("起始时间", "deliver_at", firstdata, seconddata, thirddata, fourthdata);
		} else {
			// 设置默认位置为当前年月日
			int thisYear = Calendar.getInstance().get(Calendar.YEAR);
			int thisMonth = Calendar.getInstance().get(Calendar.MONTH);
			int thisDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH) - 1;
			int thisHourOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
			String firstdata = "年,1902," + thisYear + ",false," + (thisYear - 1902);
			String seconddata = "月,1,12,true," + thisMonth;
			String thirddata = "日,1,31,true," + thisDayOfMonth;
			String fourthdata = "时,0,23,true," + thisHourOfDay;
			dialog.setData("起始时间", "deliver_at", firstdata, seconddata, thirddata, fourthdata);
		}

		dialog.setOnPickListener(new OnMyOnPickListener() {

			@Override
			public void onPickData(String key, String tag) {
				SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH");
				try {
					Date date = sFormat.parse(tag);
					if (date.getTime() > System.currentTimeMillis()) {
						toast("起始日期不能超过今天哦");
					} else {
						timeFilter.set(0, tag);
						startTime = date.getTime();
					}
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				initTimeFilterPopupWindow();
			}
		});
		dialog.show();
	}

	private void initDurDate() {
		WheelDialog dialog = new WheelDialog(this);
		// 年最大30，月12， 日31，时24
		String firstdata = "年,0," + 30 + ",true," + 0;
		String seconddata = "月,0,12,true," + 0;
		String thirddata = "日,0,31,true," + 0;
		String fourthdata = "时,0,24,true," + 0;
		dialog.setData("时间跨度", "", firstdata, seconddata, thirddata, fourthdata);

		dialog.setOnPickListener(new OnMyOnPickListener() {

			@Override
			public void onPickData(String key, String tag) {
				String[] dateArr = tag.split("-");
				int year = 0;
				int month = 0;
				int day = 0;
				int hour = 0;
				if (dateArr.length >= 3) {
					year = Integer.parseInt(dateArr[0]);
					month = Integer.parseInt(dateArr[1]);
					String[] s = dateArr[2].split(" ");
					day = Integer.parseInt(s[0]);
					hour = Integer.parseInt(s[1]);
				}
				dur = 0;
				if (year > 0) {
					dur = year * 365 * 31 * 24 * 60;
				} else if (month > 0) {
					dur = month * 31 * 24 * 60;
				} else if (day > 0) {
					dur = day * 24 * 60;
				} else if (hour > 0) {
					dur = hour * 60;
				}
				tvTimeFilter.setText("时间跨度");
				mPopupWindow.dismiss();
				loadDataDur();
			}
		});
		dialog.show();
	}

	private void loadDataDur() {
		showProgressDialog("正在加载数据");
		if (startTime == 0) {
			SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH");
			String date = sFormat.format(new Date());
			try {
				startTime = sFormat.parse(date).getTime();
			} catch (ParseException e) {
			}
		}
		loadDataType = 1;
		GatherDataLogic.getInstance().getHistoryData(this, deviceId, startTime, dur);
	}

	private void loadDataShortcut() {
		showProgressDialog("正在加载数据");
		long startTime = 0;
		SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH mm ss");
		String date = sFormat.format(new Date());
		try {
			startTime = sFormat.parse(date).getTime();
		} catch (ParseException e) {
		}
		loadDataType = 0;
		startTime -= dur * 60 * 1000l;
		GatherDataLogic.getInstance().getHistoryData(this, deviceId, startTime, dur);
	}

	private int computerShortcutDur(int position) {
		int dur = 0;
		Calendar calendar = Calendar.getInstance();
		int thisYear = calendar.get(Calendar.YEAR);
		int thisMonth = calendar.get(Calendar.MONTH);
		int thisDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		int thisHourOfDay = calendar.get(Calendar.HOUR_OF_DAY);
		int thisMinute = calendar.get(Calendar.MINUTE);
		Calendar computerCalendar = Calendar.getInstance();
		switch (position) {
//			case 2:// 最近1小时
//				computerCalendar.set(thisYear, thisMonth, thisDayOfMonth, thisHourOfDay - 1, thisMinute);
//				break;
//			case 3:// 最近8小时
//				computerCalendar.set(thisYear, thisMonth, thisDayOfMonth, thisHourOfDay - 8, thisMinute);
//				break;
//			case 4:// 当天
//				computerCalendar.set(thisYear, thisMonth, thisDayOfMonth, 0, 0);
//				break;
//			case 5:// 本月
//				computerCalendar.set(thisYear, thisMonth, 1, 0, 0);
//				break;
//			case 6:// 本季度(1-1;4-1,7-1,10-1)
//				int month = thisMonth + 1;
//				if (month >= 10) {
//					month = 10;
//				} else if (month >= 7) {
//					month = 7;
//				} else if (month >= 4) {
//					month = 4;
//				} else {
//					month = 1;
//				}
//				computerCalendar.set(thisYear, month - 1, 1, 0, 0, 0);
//				break;
//			case 7:// 当年
//				computerCalendar.set(thisYear, 0, 1, 0, 0, 0);
//				break;
			case 2://最近24小时
				computerCalendar.set(thisYear, thisMonth, thisDayOfMonth - 1, thisHourOfDay, thisMinute);
				break;
			case 3://最近一个月
				computerCalendar.set(thisYear, thisMonth - 1, thisDayOfMonth, thisHourOfDay, thisMinute);
				break;
			case 4://最近一个季度
				int month = thisMonth + 1;
				if (month >= 10) {
					month = 10;
				} else if (month >= 7) {
					month = 7;
				} else if (month >= 4) {
					month = 4;
				} else {
					month = 1;
				}
				computerCalendar.set(thisYear, month - 1, 1, 0, 0, 0);
				break;
			case 5://最近一年
				computerCalendar.set(thisYear - 1, thisMonth, thisDayOfMonth, thisHourOfDay, thisMinute);
				break;
		}
		dur = (int) ((calendar.getTimeInMillis() - computerCalendar.getTimeInMillis()) / 1000 / 60);
		return dur;
	}

	@Override
	public void handlerUI(int action, int code, Object... obj) {
		dismissDialog();
		((LineChartFragment) lineChartFragment).handlerUI(action, code, obj);
	}

}
